#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
#include <sys/socket.h>

int main(){
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in serv_addr;
    int len;
    memset(&serv_addr, 0, sizeof(serv_addr));  //每个字节都用0填充
    serv_addr.sin_family = AF_INET;  //使用IPv4地址
    serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");  //具体的IP地址
    serv_addr.sin_port = htons(54321);  //端口
    if (connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
        printf("can not connect to server.\n");
        return 0;
    }
   
    //读取服务器传回的数据
    char buffer[40];
    while (1) {
        errno = 0;
        printf("input:\n");
        scanf("%s", buffer);
        if (strcmp(buffer, "quit") == 0) {
            close(sock);
            return 0;
        }
        else
            len = write(sock, buffer, strlen(buffer));

        len = read(sock, buffer, len);
        if (len < 0) {
            printf("errno is %d\n", errno);
        }
        if (len > 0) {
            buffer[len] = '\0';
            printf("%s\n", buffer);
        }
    }
}

